package com.xcity.game.achievement.helper;

import com.xcity.game.ISystem;
import com.xcity.game.achievement.Achievement;
import com.xcity.game.achievement.Achievement.State;
import com.xcity.game.achievement.AchievementHelper;
import com.xcity.game.achievement.AchievementTemplate;

/**
 * <pre>
 * 成就类型：获得现金
 * 2个参数：①获得的现金 ②产出系统（1、奇遇；2、建筑）
 * </pre>
 * @author yang.li
 *
 */
public class GoldAddedHelper implements AchievementHelper {

	@Override
	public boolean update(Achievement refer, int... vals) {
		if (refer.getState() == State.REWARDED) {
			return false;
		}
		int _sysId = obtainSystemId(vals);
		int _val = obtainValue(vals);
		// 累加对应系统值
		String sysId = _sysId != ISystem.UNKNOWN ? String.valueOf(_sysId) : DEFAULT_VAL_KEY;
		long val = _val + refer.getValue().getLongValue(sysId);
		refer.getValue().put(sysId, val);
		// 累加总和
		if (_sysId != ISystem.UNKNOWN) {
			val = _val + refer.getValue().getLongValue(DEFAULT_VAL_KEY);
			refer.getValue().put(DEFAULT_VAL_KEY, val);
		}
		return isFinished(refer);
	}

	@Override
	public boolean isFinished(Achievement refer) {
		int sysId = obtainSystemId(refer.getTemplate());
		String key = sysId != ISystem.UNKNOWN ? String.valueOf(sysId) : DEFAULT_VAL_KEY;
		long value = obtainTargetValue(refer.getTemplate());
		if (refer.getState() == State.INITED && refer.getValue().getLongValue(key) >= value) {
			refer.setState(State.FINISHED);
			return true;
		}
		return false;
	}
	
	static int obtainSystemId(AchievementTemplate template) {
		return (int) template.getCondition(1);
	}
	
	static int obtainSystemId(int... vals) {
		if (vals != null && vals.length > 1) {
			return vals[1];
		}
		return ISystem.UNKNOWN;
	}
	
	static long obtainTargetValue(AchievementTemplate template) {
		return template.getCondition(0);
	}
	
	static int obtainValue(int... vals) {
		if (vals != null && vals.length > 0) {
			return vals[0];
		}
		return 0;
	}

}
